<?php
namespace app\middleware;
use \think\facade\Config;//引入配置
class Redirect{
    /**
     * 检测 浏览器 是否需要 301 跳转
     */
    public function handle($request, \Closure $next)
    {  
        // 前置中间件
        return $next($request);
    }

    public function run(){  
        // 检测 域名 是否需要 301 重定向
        $domn = $_SERVER['HTTP_HOST'];
        if($domn=='www.lilybearings.com' || $domn=='lilybearings.com' || $domn=='www.lily-bearings.com' || $domn=='lily-bearings.com'){
            $url = 'www.lily-bearing.com';
            $this->redirect($url);
        }
        
        $url = urldecode($_SERVER['REQUEST_URI']);
        $broken = parse_url($url);
        $path  = $broken['path'];
        $query = $broken['query'] ?? '';
       
        //资源类型 => OSS 
        if(stripos($url, '.pdf')){
            $url = 'https://image.lily-bearing.com' . str_replace('.pdf/', '.pdf', $url);
            header('HTTP/1.1 301 Moved Permanently'); 
            header("Location: $url");die;
        }
        

        // url 301 跳转
        $sql = "SELECT * FROM lily_redirect WHERE `url`='$url'";
        $resp = \think\Db::connect()->query($sql);
        if(!!$resp){
            $url =  $domn . $resp[0]['r_url']; 
            $this->redirect($url);
        }

        // url 带参数, 若url本身需要301跳转, 则参数无所谓,直接跳转
        if(!empty($query) && $path!='/sr/'){
            $sql = "SELECT * FROM lily_redirect WHERE `url`='$path'";
            $resp = \think\Db::connect()->query($sql);
            if(!!$resp){
                $url = $domn . $resp[0]['r_url'];
                $this->redirect($url, $query);
            }
        }

        // 检测 URL 是否为标准格式 /xxx/yyy/zzz/
        $path_li = array_filter(explode('/', $path));
        $str_count   = count($path_li);          # 面包屑个数
        $slash_count = substr_count($path, '/'); # 斜杠出现次数
        if($str_count>0 && $str_count+1!=$slash_count){
            $path =  '/' . implode('/', $path_li) . '/';
            $url = $domn . $path;   
            $this->redirect($url, $query);
        }
        
        // 检测 URL 是否包含大写字符[目前只检测Products] || 详情页不能带参数
        if(stristr($path, '/products/') && $path!='/products/'){
            
            // 规范URL /products/f5-10m/201/=>/products/xxx/
            $path_ = '/'. implode('/', array_slice(array_filter(explode('/', $path)), 0, 2)) . '/';
            if($path_ != $path){
                $url =  $domn . strtolower($path_);  
                $this->redirect($url);
            }

            // 大写 => 小写(301)
            if(preg_match('/[A-Z]/', $path)){
                $url =  $domn . strtolower($path);  
                $this->redirect($url);
            }

            // 详情页 url 不存在参数，广告参数除外
            if(!empty($query) && stripos($query, 'gclid=')===false){
                $url =  $domn . strtolower($path);  
                $this->redirect($url);
            }
        }
    }

    public function redirect($url, $query=''){
        $url = http_type() . $url;
        if(!empty($query)){
            if(preg_match('/^p=[a-zA-Z0-9]{1,10}$/', $query)){
                $url =  $url . '?' . $query;
            }else{
                $url_ = $url . '?' . $query;
                $status = $this->getHttpStatus($url_);
                if($status == 200){
                    $url = $url_;
                }
            }  
        }
        
        header('HTTP/1.1 301 Moved Permanently'); 
        header("Location: $url");die;
    }

    public function getHttpStatus($url) {
        $curl = curl_init();
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_NOBODY,1);
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($curl,CURLOPT_TIMEOUT,10); // timeout 10s
        curl_exec($curl);
        $re = curl_getinfo($curl,CURLINFO_HTTP_CODE);
        // dump(curl_error($curl));die;
        curl_close($curl);
        return  $re;
    }
}